// 模拟常用的高阶函数: map、every、some、reduce

// map
Array.prototype.myMap = function (fn, context) {
    let array = this;
    let results = [];
    for (let index = 0; index < array.length; index++) {
        const element = array[index];
        results.push(fn.call(context || this, element, index, array));
    }
    return results;
};

// every
Array.prototype.myEvery = function (fn, context) {
    let array = this;
    for (let index = 0; index < array.length; index++) {
        const element = array[index];
        if (!fn.call(context || this, element, index, array)) {
            return false;
        }
    }
    return true;
};

// some
Array.prototype.mySome = function (fn, context) {
    let array = this;
    for (let index = 0; index < array.length; index++) {
        const element = array[index];
        if (fn.call(context || this, element, index, array)) {
            return true;
        }
    }
    return false;
};

// reduce
Array.prototype.myReduce = function (fn, initValue, context) {
    let array = this;
    let prev = initValue;
    for (let index = 0; index < array.length; index++) {
        const element = array[index];
        prev = fn.call(context || this, prev, element, index, array);
    }
    return prev;
};

const arr = [1, 2, 3, 4];

console.log(arr.myReduce((prev, curr) => prev + curr, 0));
